import Ws from "@/assets/js/imWebsocket.js";
import { v4 as uuidv4 } from "uuid";
import Cloud from "./cloud";
import Socket from "./socket";

// import imCloud from "@/assets/js/imCloud.js";

// _xxx 带有下滑线方法名 为私有方法 不要在外部使用 可能会有修改
class WsPlugin {
  wsInfo = null;
  isOpen = false;
  msgCenter = {};
  install(Vue, options) {
    const defaultOptions = {
      autoConnect: true
    };
    const mergeOpts = Object.assign({}, defaultOptions, options);
    this.wsInfo = Ws(mergeOpts);
    if (mergeOpts.autoConnect) {
      this._bindEvents();
    }
    Vue.prototype.$cloud = new Cloud(this);
    Vue.prototype.$socket = new Socket(this);
    
  }
  _bindEvents() {
    this.wsInfo.onSocketMessage(this._proxyMsg.bind(this));
    this.wsInfo.onSocketOpen(() => {
      this.isOpen = true;
    });
  }
  _generatorToken() {
    return uuidv4();
  }
  _connect() {
    this.wsInfo.connectSocket();
    this._bindEvents();
  }
  _send(options) {
    const Token = this._generatorToken();
    const promise = new Promise((resolve, reject) => {
      const proxyOptions = {
        ...options,
        Token
      };

      this.wsInfo.sendSocketMessage({
        data: JSON.stringify(proxyOptions)
      });

      this.msgCenter[Token] = { resolve, reject };
    });
    return promise;
  }
  invoker(options) {
    return this._send(options);
  }
  _proxyMsg(msg) {
    if (msg.Code === 200) {
      this.msgCenter[msg.Token].resolve(msg.Body);
    } else {
      this.msgCenter[msg.Token].reject(msg);
    }
    delete this.msgCenter[msg.Token];
  }
}
export default WsPlugin;
